package ua.simplecoding.kievhome.dao.query;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import ua.simplecoding.kievhome.domain.Appartment;
import ua.simplecoding.kievhome.filter.AppartmentFilterVO;
import ua.simplecoding.kievhome.filter.SortFieldEnum;

/**
 * User: dmytro.fedotov
 * Date: 01.07.11
 */
public class AppartmentCriteriaBuilder extends AbstractCriteriaBuilder<AppartmentFilterVO> {

    public AppartmentCriteriaBuilder(Session session) {
        super(session, Appartment.class);
    }

    @Override
    protected void mapSortField(Criteria criteria, boolean ascending, SortFieldEnum sortFieldEnum) {
        switch (sortFieldEnum) {
            case APPARTMENT_ROOM_NUMBER:
                criteria.createAlias("appartmentDetails", "details").addOrder(getOrder(ascending, "details.roomNumber"));
                break;
            case APPARTMENT_ADDRESS_STREET:
                criteria.createAlias("appartmentAddress", "address").addOrder(getOrder(ascending, "address.streetName"));
                break;
        }
    }

    @Override
    protected void buildFilterOptions(Criteria criteria, AppartmentFilterVO filter) {
        if (!StringUtils.isBlank(filter.getStreetAddress())) {
            criteria.createAlias("appartmentAddress", "address").add(Restrictions.eq("address.streetName", filter.getStreetAddress()));
        }
        if (filter.getRoomNumber() != null) {
            criteria.createAlias("appartmentDetails", "details").add(Restrictions.eq("details.roomNumber", filter.getRoomNumber()));
        }
    }
}
